package com.liuguang.gateway.config.interceptor;

import com.liuguang.api.redis.RedisService;
import com.liuguang.common.enums.RedisPreFixEnum;
import com.liuguang.common.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: TestInterceptor
 * @Description：测试拦截器：测试调用验证码接口时候获取访问者ip。验证码获取次数限制，同一ip在3分钟内只能获取一次验证码
 * @Author: wanghr
 * Date: 3:26 PM 2020/10/13
 * Version: 1.0
 */
@Component
public class GetVerifyCodeTimeLimitInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(GetVerifyCodeTimeLimitInterceptor.class);

    @Value("${ip.real-remote-addr}")
    private String realRemoteAddr;

    @DubboReference
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取远程调用地址
        String remoteAddr = WebUtil.getIp(request);

        //保存 ip 到redis 3分钟
        String ipKey = RedisPreFixEnum.GET_VERIFY_CODE_TIME_LIMIT.getValue() + remoteAddr;
        String data = redisService.get(ipKey).getData();
        if (StringUtils.isNotEmpty(data)) {
            logger.info("每个ip三分钟内只能获取一次验证码");
            WebUtil.responseFriendly(response, -1, "每个ip三分钟内只能获取一次验证码");
            return false;
        }
        redisService.setWithTime(ipKey, "1", 3L);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
